/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/n-gram-map-reduce
   @Language: C++
   @Datetime: 20-01-14 17:29
   */

/**
 * Definition of Input:
 * template<class T>
 * class Input {
 * public:
 *     bool done(); 
 *         // Returns true if the iteration has elements or false.
 *     void next();
 *         // Move to the next element in the iteration
 *         // Runtime error if the iteration has no more elements
 *     T value();
 *        // Get the current element, Runtime error if
 *        // the iteration has no more elements
 * }
 */
class NGramMapper: public Mapper {
public:
	void Map(int n, Input<string>* input) {
		// Write your code here
		// Please directly use func 'output' to output 
		// the results into output buffer.
		// void output(string &key, int value);
		for(; !input->done(); input->next()){
			string str=input->value();
			for(int i=0; i+n<=str.length(); ++i){
				string s=str.substr(i,n);
				output(s,1);
			}
		}
	}
};


class NGramReducer: public Reducer {
public:
	void Reduce(string &key, Input<int>* input) {
		// Write your code here
		// Please directly use func 'output' to output 
		// the results into output buffer.
		// void output(string &key, int value);
		int sum=0;
		for(; !input->done(); input->next())
			sum +=input->value();
		output(key, sum);
	}
};
